# api/decorators.py

from functools import wraps
from flask import request, jsonify
from api.services import decode_access_token
from api.database import SessionLocal
from api.models import User


def token_required(f):
    """
    装饰器：验证 JWT Token 并获取用户信息
    """
    @wraps(f)
    def decorated(*args, **kwargs):
        token = None
        if 'Authorization' in request.headers:
            auth_header = request.headers['Authorization']
            try:
                token = auth_header.split(" ")[1]  # Bearer <token>
            except IndexError:
                return jsonify({'message': 'Token格式不正确'}), 401
        
        if not token:
            return jsonify({'message': 'Token缺失'}), 401
        
        payload = decode_access_token(token)
        if not payload:
            return jsonify({'message': 'Token无效'}), 401
        
        # 获取用户信息
        db = SessionLocal()
        try:
            user = db.query(User).filter(User.username == payload['identity']).first()
            if not user:
                return jsonify({'message': '用户不存在'}), 401
        finally:
            db.close()
        
        # 将用户信息传递给被装饰的函数
        return f(user, *args, **kwargs)
    
    return decorated